package main

import (
	"context"
	"flag"
	"fmt"
	"goStudy/grpc/helloword/code"
	"goStudy/grpc/helloword/helloword"
	"google.golang.org/grpc"
	"io"
	"log"
	"net"
	"time"
)

var (
	f string
)

func init()  {
	flag.StringVar(&f, "f", "", "")

}


func main()  {
	flag.Parse()

	switch f {
	case "server":
		server()
	case "client":
		client()
	case "clientChannel":
		clientChannel()

	}
}

func server()  {
	grpcServer := grpc.NewServer()
	helloword.RegisterHelloServiceServer(grpcServer,new(code.HelloServiceServer))
	lis,err:=net.Listen("tcp",":1234")
	if err != nil {
		log.Fatal(err)
	}

	grpcServer.Serve(lis)

}

func client()  {
	conn,err:=grpc.Dial("localhost:1234",grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	client:=helloword.NewHelloServiceClient(conn)

	ack,err:=client.Hello(context.Background(),&helloword.String{Value:"client hello"})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("服务端响应:",ack.Value)

}

func clientChannel()  {
	conn,err:=grpc.Dial("localhost:1234",grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	client:=helloword.NewHelloServiceClient(conn)

	stream,err:=client.Channel(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	go func() {

		num:=0
		for {
			if num== 10 {
				if err:=stream.CloseSend();err!= nil {
					log.Fatal(err)
				}

				break
			}
			if err:=stream.Send(&helloword.String{Value:"hello server"});err!= nil {
				log.Fatal(err)
			}

			time.Sleep(time.Second)
			num++
		}

	}()

	for {
		ack,err:=stream.Recv()
		if err != nil {
			if err == io.EOF {
				fmt.Println("服务端已断开连接")
				break
			}
			log.Fatal(err)
		}

		fmt.Println(ack.Value)

	}
}